package cn.comon.app.scan.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 常用转换工具类
 * @author xujf
 * @version [2013-04-12]
 */
public class UtilTools {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     *@param src 需要转换成md5的字符。
     *@return md5 转换后的md5值
     */
    public static String getStringMd5(String src) {  
        MessageDigest md;  
        StringBuilder md5 = new StringBuilder();
        try{  
            md = MessageDigest.getInstance("md5");  
            md.update(src.getBytes());              
            for (byte b : md.digest()) {
                //"%02X":md5值中的字母大写，"%02x":md5值中的字母小写
                md5.append(String.format("%02x", b));
            }
        } 
        catch (Exception e) {  
            e.printStackTrace();  
        }    
        return md5.toString();
    }

    /**
     *@param fileName 需要读取的属性文件名字，可包含路径。
     *@return properties 含有属性文件内容的Properties。
     */
    public static Properties getPropertiesFile(String fileName) {
        Properties props = null;
        try {
            InputStream ips = UtilTools.class.getClassLoader().getResourceAsStream(fileName);
            props = new Properties();
            props.load(ips);
            ips.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props;
    }

    /**
     *@param unsort_map 需要进行排序的MAP（MAP键值）。
     *@return SortedMap 按照MAP键值，排序后的结果（升序）。
     */
    public static SortedMap<String, Object> mapSortByKey(Map<String, Object> unsort_map) {

        TreeMap<String, Object> result = new TreeMap<String, Object>();

         Object[] unsort_key = unsort_map.keySet().toArray();
         Arrays.sort(unsort_key);

         for (int i = 0; i < unsort_key.length; i++) {
          result.put(unsort_key[i].toString(), unsort_map.get(unsort_key[i]));
         }
         return result.tailMap(result.firstKey());
    }
    
    /**
     * 获取客户端IP,防止反向代理改变客户端IP
     * @param request
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 
     * @param response
     * @param str 需要写入到返回流中的字符
     */
    public static void writer(HttpServletResponse response,String str){
        try {
            response.setContentType("application/json");
            //设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out= null;
            out = response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * @param afterDay 从系统时间开始需要延后的天数
     * @param timestamp 时间戳（10位）
     */
    public static int getTimestamp (int afterDay){

        String timestamp = "0";
       try {
           SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Calendar curr = Calendar.getInstance();
           curr.set(Calendar.DAY_OF_MONTH,curr.get(Calendar.DAY_OF_MONTH) + afterDay);
           Date date=curr.getTime();
           timestamp = formatter.format(date);
           Date dateq = formatter.parse(timestamp);
           timestamp = Long.toString(dateq.getTime()).substring(0,10);
       } catch (ParseException e) {
           e.printStackTrace();
       }
       return Integer.parseInt(timestamp);
    }
    
    /**
     * 
     * 取得当前日期
     * @return 返回当前日期（eg:2013-05-03）
     */
    public static String getYMD (){

        String dataYMD = "";
       try {
           SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
           Calendar curr = Calendar.getInstance();
           Date date=curr.getTime();
           dataYMD = formatter.format(date);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return dataYMD;
    }
    /**
     * 
     * 取得输入日期的时间戳
     * @return 返回输入日期的时间错
     */
    public static String getTimestamp(String datetime){
        String timestamp = null;
       try {
           SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           Date dateq = formatter.parse(datetime);
           timestamp = Long.toString(dateq.getTime()).substring(0,10);
           System.out.println(timestamp);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return timestamp;
    }
    
    /**
     * 得到一个时间延后或前移几天的时间,nowdate为时间(时间戳),delay为前移或后延的天数
     * @param nowdate 现在时间（时间戳）
     * @param delay 后移天数（eg:前移-1,后移1）
     */
    public static int getNextBeforeDay(int nowdate, int delay) {
        String timestamp = "0";
        try {
            Long tianmete = Long.parseLong(nowdate + "");
            tianmete = tianmete + 24*60*60*delay;
            timestamp =  Long.toString(tianmete);
        } catch(Exception e){
            e.printStackTrace();
        }
        return Integer.parseInt(timestamp);
    }
    /**
     * 
     * @param formatStyle 格式化格式（替换符以{0},{1}...形式表示）
     * @param formatList 替换字符
     */
    public static String formatStr (String formatStyle, List<String> formatList){

        String formatStyleTMP = formatStyle;
       try {
           // MessageFormat.format("{0}\\{1}", rootpath,dateStr);
           for (int i = 0; i < formatList.size(); i++) {
               formatStyleTMP = formatStyleTMP.replace("{" + i + "}", formatList.get(i));
           }
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return formatStyleTMP;
    }
    
    /** 
     * null的字符转换成空字符串
     * @param str 需要判断转换的字符
     */
    public static String convertNnllToString (String str){
        String result = str;
        if (result == null) {
            result = "";
        }
        return result;
    }
    
    /** 
     * 删除多余的封号;
     * @param str 需要判断转换的字符
     */
    public static String deleteComma (String str){
        String result = str;
        if (result != null) {
            if (result.startsWith(";")) {
                result = result.substring(1);
            }
            if (result.endsWith(";")) {
                result = result.substring(0,result.length() - 1);
            }
        }
        return result;
    }
}